package app.myproject.util;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import net.sf.jsr107cache.Cache;
import net.sf.jsr107cache.CacheException;
import net.sf.jsr107cache.CacheFactory;
import net.sf.jsr107cache.CacheManager;

import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.jsr107cache.GCacheFactory;


public class CacheUtil {
	
	public static void storeObject(String key, Object value) {
		Cache cache;
	        
	    try {
	    	
			Map props = new HashMap();
	        props.put(GCacheFactory.EXPIRATION_DELTA, 3600);
	        props.put(MemcacheService.SetPolicy.SET_ALWAYS, true);
	        
	        CacheFactory cacheFactory = CacheManager.getInstance().getCacheFactory();
	        cache = cacheFactory.createCache(props);
	        cache.put(key, value);
	    } catch (CacheException e) {
	        e.printStackTrace();
	    }
	}
	
	public static Object retrieveObject(String key) {
		Cache cache;
	        
	    try {
	        CacheFactory cacheFactory = CacheManager.getInstance().getCacheFactory();
	        cache = cacheFactory.createCache(Collections.emptyMap());
	        if (cache.containsKey(key)) {
	        	return cache.get(key);
	        }
	    } catch (CacheException e) {
	        e.printStackTrace();
	    }
	    return null;
	}
	
	public static void removeObject(String key) {
		Cache cache;
	        
	    try {
	        CacheFactory cacheFactory = CacheManager.getInstance().getCacheFactory();
	        cache = cacheFactory.createCache(Collections.emptyMap());
	        if (cache.containsKey(key)) {
	        	cache.remove(key);
	        }
	    } catch (CacheException e) {
	        e.printStackTrace();
	    }
	}
}
